<template>
  <div class="search-container">
    <el-form class="search-form" :model="bookSearchInfo" label-width="90px" :inline="true" ref="ruleFormRef">
      <div class="search-form-line1">
        <el-form-item label="书名">
          <el-input v-model="bookSearchInfo.title" />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="bookSearchInfo.author" />
        </el-form-item>
        <el-form-item style="margin-left: 30px;" label="出版日期">
          <el-date-picker v-model="bookSearchInfo.publication_date" type="date" format="YYYY-MM-DD" />
        </el-form-item>
      </div>
      <div class="search-form-line2">
        <el-form-item label="类型">
          <el-input v-model="bookSearchInfo.genre" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="bookSearchInfo.status">
            <el-option label="在库" value="在库" />
            <el-option label="借出" value="借出" />
          </el-select>
        </el-form-item>

        <el-form-item class="btns">
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          <el-button type="primary" plain @click="submitForm(ruleFormRef)">查询</el-button>
          <el-button v-if="checkAuth()" type="primary" @click="addNewBook()">新增图书</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>

  <myTable class="table" :columnData="columnData" :tableData="tableData">
    <template #publication_dateData="{ rowData }">
      {{ formatDate(rowData.row.publication_date).split(' ')[0] }}
    </template>
    <template #statusData="{ rowData }">
      <el-tag :type="rowData.row.status === '在库' ? 'success' : 'warning'" effect="dark" round>
        {{ rowData.row.status }}
      </el-tag>
    </template>
    <template #operateData="{ rowData }">
      <el-button style="margin-right: 10px;" type="primary" plain @click="bookDetail(rowData)">详情</el-button>
      <el-popconfirm v-if="checkAuth()" title="确认要删除吗？" @confirm="deleteBook(rowData)" confirm-button-text="是"
        cancel-button-text="否">
        <template #reference>
          <el-button type="danger" plain>删除</el-button>
        </template>
      </el-popconfirm>
    </template>
  </myTable>

  <!-- 编辑弹窗 -->
  <el-dialog v-model="dialogBookFormVisible" title="图书详情">
    <el-form :model="currentBook" label-width="90px" :inline="true">
      <el-form-item label="图书编号" v-if="flag === 'update'">
        <el-input v-model="currentBook.book_id" :disabled="true" />
      </el-form-item>
      <el-form-item label="书名">
        <el-input v-model="currentBook.title" />
      </el-form-item>
      <el-form-item label="作者">
        <el-input v-model="currentBook.author" />
      </el-form-item>
      <el-form-item label="出版日期">
        <el-date-picker v-model="currentBook.publication_date" type="date" format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="分类">
        <el-input v-model="currentBook.genre" />
      </el-form-item>
      <el-form-item label="状态" v-if="flag === 'update'">
        <el-input v-model="currentBook.status" :disabled="true" />
      </el-form-item>
      <el-form-item class="btns">
        <el-button @click="dialogBookFormVisible = false">取消</el-button>
        <el-button type="primary" @click="sureUpdate()">{{ flag === 'add' ? '新增' : '保存' }}</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import myTable from '@/components/table/index.vue'
import { columnDataType, tableDataType } from '@/components/table/index.d'
import { getBookList, updateBook, createBook, delBook } from '@/request/api'
import { formatDate, checkAuth } from '@/utils/index'

const ruleFormRef = ref<FormInstance>()

onMounted(() => {
  getList()
})

const getList = () => {
  getBookList(bookSearchInfo).then((res: any) => {
    console.log(res);
    if (res.code === 200) {
      tableData.list = res.data
      currentPage.total = res.data.length
    } else {
      ElNotification({
        title: res.msg,
        type: 'error',
        duration: 1000
      })
    }

  }).catch((err) => {
    console.log(err);
  })
}

// 物资信息查询关键字
const bookSearchInfo = reactive({
  title: '',
  author: '',
  publication_date: '',
  genre: '',
  status: ''
})
// 分页器相关参数
const currentPage = reactive({
  size: 10,
  current: 1,
  total: 0
})

// 查询图书信息
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      getBookList(bookSearchInfo).then((res: any) => {
        console.log(res);
        if (res.code === 200) {
          ElNotification({
            title: res.msg,
            type: 'success',
            duration: 1000
          })
          tableData.list = res.data
          currentPage.total = res.data.length
        } else {
          ElNotification({
            title: res.msg,
            type: 'error',
            duration: 1000
          })
        }

      }).catch((err) => {
        console.log(err);
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  bookSearchInfo.title = ''
  bookSearchInfo.author = ''
  bookSearchInfo.publication_date = ''
  bookSearchInfo.genre = ''
  bookSearchInfo.status = ''
}

// 表格
const columnData = reactive<columnDataType<any>[]>([
  {
    property: 'book_id',
    label: '图书编号',
  },
  {
    property: 'title',
    label: '书名',
  },
  {
    property: 'author',
    label: '作者',
  },
  {
    property: 'publication_date',
    label: '出版日期',
    customData: "publication_dateData",
  },
  {
    property: 'genre',
    label: '类型',
  },
  {
    property: 'status',
    label: '状态',
    customData: "statusData",
  },
  {
    property: 'operate',
    label: '操作',
    width: 240,
    fixed: 'right',
    customData: "operateData",
  }
])

// 表格
const tableData = reactive<tableDataType<any>>({
  list: [],
  needPaging: false,
  paging: {
    total: currentPage.total,
    currentPage: currentPage.current,
    changeFn: (val: number) => {
      console.log(val);
      currentPage.current = val
    },
    sizeFn: (val: number) => {
      console.log(val);
      currentPage.size = val
    }
  }
})


const flag = ref('add')
const dialogBookFormVisible = ref(false)
const currentBook = reactive({
  book_id: 0,
  title: '',
  author: '',
  publication_date: '',
  genre: '',
  status: ''
})
// 图书详情
const bookDetail = (rowData: any) => {
  console.log(rowData);
  dialogBookFormVisible.value = true
  flag.value = 'update'
  currentBook.book_id = parseInt(rowData.row.book_id.toString())
  currentBook.title = rowData.row.title
  currentBook.author = rowData.row.author
  currentBook.publication_date = rowData.row.publication_date
  currentBook.genre = rowData.row.genre
  currentBook.status = rowData.row.status
}
// 删除图书
const deleteBook = (rowData: any) => {
  delBook({ book_id: rowData.row.book_id }).then((res: any) => {
    if (res.code === 200) {
      ElNotification({
        title: res.msg,
        type: 'success',
        duration: 1000
      })
      getList()
    } else {
      ElNotification({
        title: res.msg,
        type: 'error',
        duration: 1000
      })
    }
  }).catch((err) => {
    console.log(err);
  })
}
// 新增图书
const addNewBook = () => {
  dialogBookFormVisible.value = true
  flag.value = 'add'
  currentBook.title = ''
  currentBook.author = ''
  currentBook.publication_date = ''
  currentBook.genre = ''
  currentBook.status = ''
}
// 确认更新或者新增
const sureUpdate = () => {
  // 更新图书
  if (flag.value === 'update') {
    updateBook(currentBook).then((res: any) => {
      if (res.code === 200) {
        ElNotification({
          title: res.msg,
          type: 'success',
          duration: 1000
        })
      } else {
        ElNotification({
          title: res.msg,
          type: 'error',
          duration: 1000
        })
      }
      dialogBookFormVisible.value = false
      getList()
    }).catch((err) => {
      console.log(err);
    })
  }
  // 新增图书
  if (flag.value === 'add') {
    createBook(currentBook).then((res: any) => {
      if (res.code === 200) {
        ElNotification({
          title: res.msg,
          type: 'success',
          duration: 1000
        })
      } else {
        ElNotification({
          title: res.msg,
          type: 'error',
          duration: 1000
        })
      }
      dialogBookFormVisible.value = false
      getList()
    }).catch((err) => {
      console.log(err);
    })
  }

}

</script>

<style scoped>
.search-container {
  border-bottom: 3px solid rgb(245, 245, 245);
  margin-bottom: 20px;
}

.btns {
  margin-left: 60px;
}

.btn-group {
  margin-right: 12px;
}

.table {
  border-top: 3px solid rgb(245, 245, 245);
}
</style>